package com.tcxhb.job.core.schedule.workflow;

import com.tcxhb.job.dao.dataobject.JobInfoDO;
import com.tcxhb.job.dao.dataobject.JobInstanceDO;
import com.tcxhb.job.dao.dataobject.JobMachineDO;
import com.tcxhb.job.common.model.MiscResult;
import com.tcxhb.job.core.convert.JobConvert;
import com.tcxhb.job.core.schedule.execute.JobRunContext;
import com.tcxhb.job.core.service.job.JobInfoService;
import com.tcxhb.job.core.service.job.JobInstanceService;
import com.tcxhb.job.core.utils.TraceUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Auther: tcxhb
 * @Date: 2023/11/12
 */
@Component
public class InstanceBulidFlow implements FlowHandler<JobRunContext> {
    @Autowired
    private JobInstanceService jobInstanceService;
    @Autowired
    private JobInfoService jobInfoService;
    @Autowired
    private JobConvert convert;

    @Override
    public MiscResult handle(JobRunContext cxt) {
        //批量创建数据库
        List<JobInstanceDO> list = new ArrayList<>();
        for (int i = 0; i < cxt.getShardingNum(); i++) {
            JobMachineDO machineDO = getMachine(i, cxt.getMachineList());
            JobInstanceDO instance = buildInstance(cxt, machineDO, i + 1);
            list.add(instance);
        }
        cxt.setInstanceList(list);
        return MiscResult.suc();
    }

    /**
     * @param cxt
     * @return
     */
    private JobInstanceDO buildInstance(JobRunContext cxt, JobMachineDO machineDO, Integer shardingNo) {
        //插入执行实例
        JobInfoDO jobDO = cxt.getJobDO();
        Long scheduleTime = cxt.getReq().getScheduleTime();
        //创建实例
        JobInstanceDO instanceDO = convert.toInstance(jobDO, shardingNo);
        instanceDO.setScheduleTime(scheduleTime);
        String traceId = TraceUtils.buildTraceId(jobDO.getId(), instanceDO.getScheduleTime(), shardingNo);
        instanceDO.setTraceId(traceId);
        if (machineDO != null) {
            instanceDO.setMachineAddr(machineDO.httpAddress());
        }
        //并且刷新下一次执行
        return instanceDO;
    }

    public JobMachineDO getMachine(int idx, List<JobMachineDO> list) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        int size = list.size();
        return list.get(idx % size);
    }
}
